package jmu.edu.yjc.Interceptor;

import jmu.edu.yjc.Utils.IpUtils;
import jmu.edu.yjc.Utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author yjc
 * @date 2023/4/9 16:40
 */
@Slf4j
@Component
public class PageViewInterceptor implements HandlerInterceptor {
    @Resource
    private RedisCache redisCache;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = IpUtils.getIpAddr(request);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        Long ipLong = ipToLong(ip);
        log.info("key:{} ,ip: {}, ipLong: {}" , format, ip,  ipLong);
        redisCache.setHyperLogLog(format, ipLong);
        return true;
    }
    private Long ipToLong(String ipStr) {

        long ipLong = 0;

        if (ipStr != null && ipStr.length() > 0) {
            //将ip(点分十进制的形式 a.b.c.d) 地址按.分割
            String[] ipSplit = ipStr.split("\\.");
            try {
                if (ipSplit.length != 4) {
                    throw new Exception("IP Format Error");
                }
                for (int i = 0; i < ipSplit.length; i++) {
                    int temp = Integer.parseInt(ipSplit[i]);
                    ipLong += temp * (1L << (ipSplit.length - i - 1) * 8);
                }
            } catch (Exception e) {
                log.error("ip address to long type Error :{}", e.getMessage());
            }
        } else {
            log.info("ip address is null or is ''");
        }
        return ipLong;

    }
}
